# -*- coding:utf-8 -*-

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.utils.translation import ugettext_lazy as _
from disn.utilities import *
import logging, datetime, time, qrcode, os
from django.db import IntegrityError
from uuid import uuid4
from disn.settings import PROJECT_PATH, BASE_DIR
from django.db.models import Count, Q
from xpinyin import Pinyin
from wechatpy.events import UnsubscribeEvent
from disn.settings import redis_instance

pinyin = Pinyin()
GENDERS = (('1', '男'), ('2', '女'), )

STARS = (
    ('0', '☆☆☆☆☆'),
    ('1', '★☆☆☆☆'),
    ('2', '★★☆☆☆'),
    ('3', '★★★☆☆'),
    ('4', '★★★★☆'),
    ('5', '★★★★★'),
)

CATEGORIES = (
    ('0', '工作人员'),
    ('1', '微信关注'),
    ('2', '批量导入'),
    ('9', '其它'),
)

CONFIG_CATEGORIES = (
    ('1', '近期文章'),
    ('2', '字符串常量'),
    ('3', '微信自定义变量'),
    ('4', '微信菜单定义'),
)

CONFIG_CONTENT_TYPE = (
    ('', '请选择'),
    ('text', '文本'),
    ('news', '卡片'),
    ('voice', '语音'),
    ('image', '图片'),
    ('video', '视频'),
)

CONFIG_STATUS = (
    ('0', '禁用'),
    ('1', '启用'),
)

MSG_TYPES = (
    ('1', '接收客户消息'),
    ('2', '系统回复消息'),
    ('3', '用户查看汇率走势'),
    ('4', '管理员回复消息'),
)

class Star(models.Model):
    name = models.CharField(max_length=50, blank=True, null=True, verbose_name='姓名')
    name_pinyin = models.CharField(max_length=100, blank=True, null=True, verbose_name='拼音')
    gender = models.CharField(max_length=2, blank=True, null=True, verbose_name='性别', choices=GENDERS)
    job = models.CharField(max_length=50, blank=True, null=True, verbose_name='职业')
    nationality = models.CharField(max_length=20, blank=True, null=True, verbose_name='国籍')
    birth_date = models.DateField(verbose_name='出生日期', blank=True, null=True)
    constellation = models.CharField(max_length=20, blank=True, null=True, verbose_name='星座')
    height = models.IntegerField(default=-1,verbose_name='身高')
    score = models.FloatField(verbose_name='得分')
    avatar = models.CharField(max_length=300, blank=True, null=True, verbose_name='照片', default='')
    face_token = models.CharField(max_length=100, blank=True, null=True, verbose_name='Face Token')
    create_at = models.DateTimeField(auto_now_add=True,verbose_name='创建时间')
    modify_at = models.DateTimeField(blank=True,null=True,verbose_name='修改时间')

    class Meta:
        verbose_name = '明星库'
        verbose_name_plural = '明星库'

    def save(self, *args, **kwargs):
        self.modify_at = datetime.datetime.now()
        return super(Star, self).save(*args, **kwargs)

    def __str__(self):
        return '%s' % self.name


class WxConfig(models.Model):
    key = models.CharField(max_length=50, blank=True, null=True, unique=True, verbose_name='名称')
    value = models.TextField(blank=True, null=True, verbose_name='内容')
    category = models.CharField(max_length=2, verbose_name='类别', choices=CONFIG_CATEGORIES)
    reply_type = models.CharField(max_length=10, verbose_name='微信回复类型', choices=CONFIG_CONTENT_TYPE, null=True,
                                  blank=True, default='text')
    datetime_created = models.DateTimeField(blank=True, null=True, verbose_name='时间')
    status = models.CharField(max_length=2, verbose_name='状态', default='1', choices=CONFIG_STATUS)
    remark = models.TextField(blank=True, null=True, verbose_name='备注')

    def split_as_list(self):
        return self.value.split('|')

    @staticmethod
    def get_latest_articles():
        return WxConfig.objects.filter(category='1', status='1').order_by('-datetime_created')[:10]

    class Meta:
        verbose_name = '微信参数配置'
        verbose_name_plural = '微信参数配置'

    def save(self, *args, **kwargs):
        self.datetime_created = datetime.datetime.now()
        return super(WxConfig, self).save(*args, **kwargs)

    def __str__(self):
        return '%s' % self.key


class UserProfile(models.Model):
    user = models.OneToOneField(User, unique=True, related_name='profile')
    owner = models.ForeignKey(User, blank=True, null=True, limit_choices_to={'is_staff': True}, verbose_name='客户经理ID', related_name='owner')
    assistants = models.CharField(max_length=100, blank=True, null=True, verbose_name='共享访问IDs',
                                  help_text='多个ID之间用逗号","隔开')
    openid = models.CharField(max_length=30, blank=True, null=True, verbose_name='微信OpenID')
    unionid = models.CharField(max_length=30, blank=True, null=True, verbose_name='微信UnionID')
    # cctalk_id = models.CharField(max_length=50, default='0', blank=True, null=True, verbose_name='CCTalk帐号')
    avatar = models.ImageField(upload_to='./photo/peoples/', verbose_name='头像', blank=True, null=True)
    headimgurl = models.CharField(max_length=300, blank=True, null=True, verbose_name='微信头像', default='')
    truename = models.CharField(max_length=30, blank=True, null=True, verbose_name='真实姓名', default='')
    nickname = models.CharField(max_length=30, blank=True, null=True, verbose_name='昵称', default='')
    phone = models.CharField(max_length=30, blank=True, null=True, verbose_name='手机', default='')
    city = models.CharField(max_length=20, blank=True, null=True, verbose_name='城市', default='')
    birth_date = models.DateField(verbose_name='出生日期', blank=True, null=True)
    gender = models.CharField(max_length=2, blank=True, null=True, verbose_name='性别', choices=GENDERS)
    id_card = models.CharField(max_length=20, blank=True, null=True, verbose_name='身份证', default='')
    description = models.TextField(blank=True, null=True, verbose_name='个人描述', default='')
    category = models.CharField(max_length=2, verbose_name='用户类别', choices=CATEGORIES, default='6')
    school = models.CharField(max_length=50, blank=True, null=True, verbose_name='单位或学校', default='')
    blog = models.CharField(max_length=50, blank=True, null=True, verbose_name='博客', default='')
    qq = models.CharField(max_length=20, blank=True, null=True, verbose_name='QQ号码', default='')
    weibo = models.CharField(max_length=20, blank=True, null=True, verbose_name='微博', default='')
    douban = models.CharField(max_length=20, blank=True, null=True, verbose_name='豆瓣', default='')
    email_verified = models.BooleanField(default=False, verbose_name='邮件确认?')
    mobile_verified = models.BooleanField(default=False, verbose_name='手机确认?')
    subscribed = models.BooleanField(default=False, verbose_name='关注公众号?')
    subscribe_time = models.DateTimeField(blank=True, null=True, verbose_name='关注时间')
    subscribe_scene = models.CharField(max_length=50, blank=True, null=True, verbose_name='关注类型')
    subscribe_referrer = models.ForeignKey(User, blank=True, null=True, verbose_name='推荐人', related_name='referrer')
    addr = models.CharField(max_length=100, blank=True, null=True, verbose_name='详细地址', default='')
    intro = models.TextField(blank=True, null=True, verbose_name='简介')
    stars = models.CharField(max_length=2, blank=True, null=True, verbose_name='重要程度', default='0', choices=STARS)
    point = models.IntegerField(verbose_name='积分', default=0)
    class Meta:
        verbose_name = _('用户Profile')
        verbose_name_plural = _('用户Profile')

    def __str__(self):
        return self.nickname
        # return '%s' % self.user.username

    @staticmethod
    def get_user_by_unionid(unionid):
        try:
            user = UserProfile.objects.get(unionid=unionid)
        except UserProfile.DoesNotExist:
            return None
        else:
            return user

    @staticmethod
    def get_subscribed_user_by_openid(openid):
        try:
            user = UserProfile.objects.get(openid=openid, subscribed=True)
        except UserProfile.DoesNotExist:
            return None
        else:
            return user;

    @staticmethod
    def get_user_by_openid(openid):
        try:
            user = UserProfile.objects.get(openid=openid)
        except UserProfile.DoesNotExist:
            return None
        else:
            return user

    @staticmethod
    def get_existed_wechat_openid():
        user_set = UserProfile.objects.exclude(openid__isnull=True).exclude(openid__exact='')
        existed_wechat_openids = []
        for user in user_set:
            existed_wechat_openids.append(user.openid)
        return existed_wechat_openids

    @staticmethod
    def sync_user_avatar(user_json):
        user = UserProfile.objects.get(openid=user_json['openid'])
        user.avatar = user_json['headimgurl']
        user.save()

    @staticmethod
    def get_create_or_update_user(user_json, msg, force_update=False):
        try:
            user = UserProfile.objects.get(openid=user_json['openid'])  # User.objects.get(email=email)
            if isinstance(msg, UnsubscribeEvent):
                user.subscribed = False
                user.save()
                return user
            else:
                if force_update:
                    user.subscribed = True
                    user.nickname = filter_emoji(user_json.get('nickname', user_json['openid']))
                    user.city = '%s%s' % (user_json.get('province',''), user_json.get('city',''))
                    user.gender = str(user_json.get('sex','1'))
                    user.description = filter_emoji(user_json.get('remark',''))
                    if user.category is None or user.category == '':
                        user.category = '1'
                    if user.owner is None:
                        try:
                            admin_user = User.objects.get(username='admin')
                        except User.DoesNotExist:
                            admin_user = User.objects.create_superuser('admin', 'jean.zhang@outlook.com', 'pass')
                        user.owner = admin_user
                    if 'subscribe' in user_json:
                        if user_json['subscribe'] == 1:
                            user.subscribed = True
                        else:
                            user.subscribed = False
                    user.headimgurl = user_json.get('headimgurl', '')
                    user.subscribe_scene = user_json.get('subscribe_scene','')
                    user.save()
                return user
        except UserProfile.DoesNotExist:  # 新建用户
            openid = user_json['openid']
            if isinstance(msg, UnsubscribeEvent):
                return None
            if user_json['remark'] and user_json['remark'] != '':
                saved_user_name = filter_emoji(user_json['remark'])
            else:
                saved_user_name = filter_emoji(user_json['nickname'])
            try:
                user = User.objects.create_user(username=openid, password=gen_password(6))
                user.first_name = saved_user_name
                user.save()
                profile = user.profile
                profile.openid = openid
                # profile.unionid = user_json['unionid'] # 只有在用户将公众号绑定到微信开放平台帐号后，才会出现该字段。
                profile.headimgurl = user_json.get('headimgurl','')
                profile.city = '%s%s' % (user_json.get('province',''), user_json.get('city',''))
                profile.nickname = saved_user_name
                profile.gender = str(user_json.get('sex','1'))
                profile.description = filter_emoji(user_json['remark'])
                profile.category = '1'
                profile.owner_id = 1
                profile.subscribed = True
                subscribe_time = int(user_json.get('subscribe_time',0))
                time_local = time.localtime(subscribe_time)
                profile.subscribe_time = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
                user.subscribe_scene = user_json.get('subscribe_scene','')
                profile.save()
            except IntegrityError:
                print ("Oops! IntegrityError. Try again...")
                print (user_json)
                profile = UserProfile.objects.get(openid=user_json['openid'])
            return profile

    def userid(self):
        return self.user.username

    userid.short_description = '用户名'

    def email(self):
        return self.user.email

    email.short_description = '电子邮件'

    def rm(self):
        if self.owner:
            return self.owner.username + '(' + self.owner.last_name + self.owner.first_name + ')'
        else:
            return '未指定'

    rm.short_description = '客户经理'

    # def avatar_thumb(self):
    #   if self.avatar.name.find('photo/peoples') >= 0:
    #       return '<img style="width:150px;height:150px;" src="/media/%s" />' % self.avatar
    #   else:
    #       return '<img style="width:150px;height:150px;" src="%s" />' % self.avatar
    # avatar_thumb.allow_tags = True
    # avatar_thumb.short_description = '头像照片'

    def create_user_profile(sender, instance, created, **kwargs):
        if created:
            profile, created = UserProfile.objects.get_or_create(user=instance)

    post_save.connect(create_user_profile, sender=User)


def wechat_upload_to(instance, filename):
    return './wechat/attachments/%s/%s' % (instance.user.user.username, filename)


class WechatLog(models.Model):
    user = models.ForeignKey(UserProfile, verbose_name='用户')
    created_at = models.DateTimeField(auto_now_add=True, editable=False, verbose_name='时间')
    content = models.TextField(verbose_name='内容', null=True, blank=True)
    attachment = models.FileField(upload_to=wechat_upload_to, verbose_name='附件', blank=True, null=True,
                                  help_text='语音转换链接：http://www.convertfiles.com/convert/audio/AMR-to-MP3.html')
    msg_type = models.CharField(max_length=1, choices=MSG_TYPES, verbose_name='消息类型')

    class Meta:
        verbose_name = _('微信记录')
        verbose_name_plural = _('微信记录')

    def __str__(self):
        return '与用户[%s]的会话 %s' % (self.user.truename, str(self.created_at))



LINKSTARS_CHANNEL_ITEMS = (
    ('1915', '亲近母语官网'),
    ('1916', 'QQ'),
    ('1917', '环紫金山微博'),
    ('1918', '舜易咨询官网'),
    ('1919', '环紫金山的微信'),
    ('1920', '环紫金山的博客'),
    ('2923', '每周精选购'),
    ('3117', 'ztm.me'),
)

ARTICLE_FROM_ITEMS = (
    ('0','请选择'),
    ('1','什么值得买'),
    ('2','买个便宜货'),
    ('5','后台输入'),
)

class Brand(models.Model):
    name = models.CharField(max_length=50, blank=True, null=True, verbose_name='品牌名称')
    country = models.CharField(max_length=20, blank=True, null=True, verbose_name='品牌地域')
    active = models.BooleanField(default=False, verbose_name='有效')
    order = models.IntegerField(default=-1, verbose_name='排序')
    create_at = models.DateTimeField(auto_now_add=True,verbose_name='创建时间')
    modify_at = models.DateTimeField(blank=True,null=True,verbose_name='修改时间')
    remarks = models.TextField(blank=True,null=True,verbose_name='备注')

    def save(self, *args, **kwargs):
        self.modify_at = datetime.datetime.today()
        return super(Brand, self).save(*args, **kwargs)

    class Meta:
        verbose_name = '商品品牌'
        verbose_name_plural = '商品品牌'
        ordering = ('-modify_at', '-create_at')

    def __str__(self):
        return self.name

class Mall(models.Model):
    name = models.CharField(max_length=50, blank=True, null=True, verbose_name='商城名称')
    code = models.CharField(max_length=20, blank=True, null=True, verbose_name='商城代码')
    pinyin = models.CharField(max_length=100, blank=True, null=True, verbose_name='拼音代码')
    active = models.BooleanField(default=False, verbose_name='有效')
    order = models.IntegerField(default=-1, verbose_name='排序')
    plan_code = models.CharField(max_length=10, blank=True, null=True, verbose_name='推广计划')
    plan_code_wx = models.CharField(max_length=10, blank=True, null=True, verbose_name='微信推广计划')
    plan_code_mb = models.CharField(max_length=10, blank=True, null=True, verbose_name='移动推广计划')
    plan_active = models.BooleanField(default=False, verbose_name='计划有效')
    mall_url = models.CharField(max_length=100, blank=True, null=True, verbose_name='商城URL')
    mall_url_wx = models.CharField(max_length=100, blank=True, null=True, verbose_name='微信商城URL')
    mall_url_mb = models.CharField(max_length=100, blank=True, null=True, verbose_name='移动商城URL')
    create_at = models.DateTimeField(auto_now_add=True,verbose_name='创建时间')
    modify_at = models.DateTimeField(blank=True,null=True,verbose_name='修改时间')
    remarks = models.TextField(blank=True,null=True,verbose_name='备注')

    def save(self, *args, **kwargs):
        self.modify_at = datetime.datetime.today()
        if not self.id or not self.plan_code:
            if self.name.find('京东') >= 0:
                self.plan_code = '156'
                self.plan_code_wx = '158'
                self.plan_code_mb = '157'
                self.mall_url = 'www.jd.com'
                self.mall_url_mb = 'm.jd.com'
                self.mall_url_wx = 'wq.jd.com'
                self.active = self.plan_active = True
            elif self.name.find('苏宁') >= 0:
                self.plan_code = self.plan_code_wx = self.plan_code_mb = '150'
                self.mall_url = self.mall_url_mb = self.mall_url_wx = 'www.suning.com'
                self.active = self.plan_active = True
            elif self.name.find('1号店') >= 0 or self.name.find('一号店') >= 0:
                self.plan_code = '73'
                self.plan_code_mb = self.plan_code_wx = '83'
                self.mall_url = 'www.yhd.com'
                self.mall_url_mb = self.mall_url_wx = 'm.yhd.com'
                self.active = self.plan_active = True
            elif self.name.find('考拉') >= 0:
                self.plan_code = self.plan_code_wx = self.plan_code_mb = '42'
                self.mall_url = self.mall_url_mb = self.mall_url_wx = 'www.kaola.com'
                self.active = self.plan_active = True
            elif self.name.find('国美') >= 0:
                self.plan_code = self.plan_code_wx = self.plan_code_mb = '95'
                self.mall_url = self.mall_url_mb = self.mall_url_wx = 'www.gome.com.cn'
                self.active = self.plan_active = True
            elif self.name.find('中粮') >= 0:
                self.plan_code = self.plan_code_wx = self.plan_code_mb = '38'
                self.mall_url = self.mall_url_mb = self.mall_url_wx = 'www.womai.com'
                self.active = self.plan_active = True
            elif self.name.find('当当') >= 0:
                self.plan_code = '340'
                self.plan_code_wx = self.plan_code_mb = '380'
                self.mall_url = 'www.dangdang.com'
                self.mall_url_wx = self.mall_url_mb = 'm.dangdang.com'
                self.active = self.plan_active = True
            elif self.name.find('bodyguard') >= 0: # 德国BA保镖药房中文官网CPS
                # https://union.linkstars.com/web.php?m=plan&a=plan_detail&plan_id=103
                self.plan_code = self.plan_code_wx = self.plan_code_mb = '103'
                self.mall_url = self.mall_url_wx = self.mall_url_mb = 'www.ba.de'
                self.active = self.plan_active = True
            elif self.name == '德国药房apo.com':
                # https://union.linkstars.com/web.php?m=plan&a=plan_detail&plan_id=93
                self.plan_code = self.plan_code_wx = self.plan_code_mb = '93'
                self.mall_url = self.mall_url_wx = self.mall_url_mb = 'cn.apo.com'
                self.active = self.plan_active = True
        if self.name:
            self.code   = pinyin.get_initials(self.name.replace(' ','-'), '')
            self.pinyin = pinyin.get_pinyin(self.name.replace(' ','-'))
        return super(Mall, self).save(*args, **kwargs)

    class Meta:
        verbose_name = '电商名称'
        verbose_name_plural = '电商名称'
        ordering = ('-modify_at', '-create_at')

    def __str__(self):
        # return self.name
        return (self.name[:6] + '..') if len(self.name) > 6 else self.name



class Channel(models.Model):
    name = models.CharField(max_length=50, blank=True, null=True, verbose_name='频道名称')
    code = models.CharField(max_length=100, blank=True, null=True, verbose_name='频道代码')
    pinyin = models.CharField(max_length=100, blank=True, null=True, verbose_name='频道全拼')
    parent = models.ForeignKey("self", blank=True, null=True, verbose_name='上层频道')
    active = models.BooleanField(default=False, verbose_name='有效')
    order = models.IntegerField(default=-1, verbose_name='排序')
    create_at = models.DateTimeField(auto_now_add=True,verbose_name='创建时间')
    modify_at = models.DateTimeField(blank=True,null=True,verbose_name='修改时间')
    remarks = models.TextField(blank=True,null=True,verbose_name='备注')

    def save(self, *args, **kwargs):
        self.modify_at = datetime.datetime.today()
        if self.name:
            self.code = pinyin.get_initials(self.name, '')
            self.pinyin = pinyin.get_pinyin(self.name)
        return super(Channel, self).save(*args, **kwargs)

    class Meta:
        verbose_name = '商品频道'
        verbose_name_plural = '商品频道'
        ordering = ('-modify_at', '-create_at')

    def __str__(self):
        return self.name

class Category(models.Model):
    name = models.CharField(max_length=50, blank=True, null=True, verbose_name='分类名称')
    code = models.CharField(max_length=100, blank=True, null=True, verbose_name='分类代码')
    pinyin = models.CharField(max_length=100, blank=True, null=True, verbose_name='分类全拼')
    parent = models.ForeignKey("self", blank=True, null=True, verbose_name='上层分类')
    active = models.BooleanField(default=True, verbose_name='有效')
    order = models.IntegerField(default=-1, verbose_name='排序')
    create_at = models.DateTimeField(auto_now_add=True,verbose_name='创建时间')
    modify_at = models.DateTimeField(blank=True,null=True,verbose_name='修改时间')
    remarks = models.TextField(blank=True,null=True,verbose_name='备注')

    def save(self, *args, **kwargs):
        self.modify_at = datetime.datetime.today()
        if self.name:
            self.code = pinyin.get_initials(self.name, '')
            self.pinyin = pinyin.get_pinyin(self.name)
        return super(Category, self).save(*args, **kwargs)

    class Meta:
        verbose_name = '商品分类'
        verbose_name_plural = '商品分类'
        ordering = ('-modify_at', '-create_at')

    def __str__(self):
        return self.name

    @staticmethod
    def get_name_by_pinyin(pinyin):
        if pinyin and len(pinyin) > 0:
            name = redis_instance.get(pinyin)
            if not name:
                try:
                    category = Category.objects.get(pinyin=pinyin)
                    name = category.name
                    redis_instance.set(name=pinyin, value=name)
                except Category.DoesNotExist as e:
                    log.error(e)
                except Exception as e:
                    log.error(e)
            return name
        else:
            return None

'''
http://faxian.smzdm.com/json_more?type=a&timesort=1498481740
http://www.smzdm.com/homepage/json_more?timesort=149973056152&p=3
http://www.smzdm.com/jingxuan/json_more?timesort=1499733011&filter=s0f0t0b0d0r0p0
http://haitao.smzdm.com/json_more?timesort=1499690048
http://www.smzdm.com/youhui/json_more?timesort=1499732527
'''
class Item(models.Model):
    article_id = models.CharField(max_length=20, unique=True, verbose_name='编号')
    article_title = models.CharField(max_length=200, blank=True, null=True, verbose_name='标题')
    article_title_pinyin = models.CharField(max_length=500, blank=True, null=True, verbose_name='标题拼音')
    article_price = models.CharField(max_length=50, blank=True, null=True, verbose_name='价格')
    article_summary = models.TextField(blank=True, null=True, verbose_name='商品简介')
    article_content = models.TextField(blank=True, null=True, verbose_name='详细内容')
    article_mall = models.ForeignKey(Mall, blank=True, null=True, verbose_name='商城')
    article_pic = models.CharField(max_length=100, blank=True, null=True, verbose_name='配图')
    article_pic_style = models.CharField(max_length=100, blank=True, null=True, verbose_name='配图样式')
    article_date = models.CharField(max_length=50, blank=True, null=True, verbose_name='显示日期')
    article_url = models.CharField(max_length=200, blank=True, null=True, verbose_name='值得买链接')
    article_link = models.CharField(max_length=200, blank=True, null=True, verbose_name='跳转链接')
    article_channel = models.ForeignKey(Channel, blank=True, null=True, verbose_name='频道') # j:article_channel, f:article_channel_note
    top_category = models.ForeignKey(Category, blank=True, null=True, verbose_name='分类大类') # f:article_top_category
    sub_category = models.CharField(max_length=50, blank=True, null=True, verbose_name='分类子类')
    article_from = models.CharField(max_length=2, blank=True, null=True, verbose_name='条目来自', choices=ARTICLE_FROM_ITEMS)
    article_category = models.CharField(max_length=20, blank=True, null=True, verbose_name='条目分类') # faxian, jingxuan, haitao
    rmb_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True, verbose_name='人民币价格')
    brand = models.ForeignKey(Brand, blank=True, null=True, verbose_name='商标')
    commodity_sku = models.CharField(max_length=50, blank=True, null=True, verbose_name='商品SK')
    commodity_url = models.CharField(max_length=200, blank=True, null= True, verbose_name='商品原URL')
    commodity_url_refer = models.CharField(max_length=500, blank=True, null= True, verbose_name='商品推荐URL')
    commodity_url_refer_mb = models.CharField(max_length=500, blank=True, null= True, verbose_name='商品推荐移动URL')
    qiniu_pic = models.CharField(max_length=100, blank=True, null=True, verbose_name='七牛配图')
    # recommend_url = models.CharField(max_length=300, blank=True, null= True, verbose_name='推荐链接')
    # recommend_url_mb = models.CharField(max_length=300, blank=True, null= True, verbose_name='移动推荐链接')
    remark = models.TextField(blank=True, null=True, verbose_name='备注')
    error = models.BooleanField(default=False, verbose_name='出错')
    error_msg = models.TextField(blank=True, null=True, verbose_name='错误消息')
    active = models.BooleanField(default=False, verbose_name='有效')
    special = models.BooleanField(default=False, verbose_name='专题页')
    expired = models.BooleanField(default=False, verbose_name='过期')
    create_at = models.DateTimeField(auto_now_add=True,verbose_name='创建时间')
    modify_at = models.DateTimeField(blank=True,null=True,verbose_name='修改时间')
    crawl_cnt = models.IntegerField(default=0, blank=True, null=True, verbose_name='爬取次数')
    timesort = models.IntegerField(verbose_name='抓取批次')

    def save(self, *args, **kwargs):
        self.modify_at = datetime.datetime.today()
        if self.article_title:
            self.article_title_pinyin = pinyin.get_initials(self.article_title, '')
        return super(Item, self).save(*args, **kwargs)

    class Meta:
        verbose_name = '优惠商品目录'
        verbose_name_plural = '优惠商品目录'
        ordering = ('-create_at',)

    def __str__(self):
        # return str(self.article_title)
        return (self.article_title[:25] + '..') if len(self.article_title) > 25 else self.article_title

    def as_json(self):
        return dict(
            id = self.id,
            article_id = self.article_id,
            article_title = self.article_title,
            article_price = self.article_price,
            article_summary = self.article_summary,
            article_mall = self.article_mall.name,
            article_date = self.article_date,
            qiniu_pic = self.qiniu_pic,
            # article_pic_style = self.article_pic_style if self.article_pic_style else 'width="200px" height="200px"',
            commodity_sku = self.commodity_sku,
            commodity_url = self.commodity_url,
            commodity_url_refer = self.commodity_url_refer,
            create_at = self.create_at.strftime('%Y-%m-%d %H:%M:%S') if self.create_at else None,
            modify_at = self.modify_at.strftime('%Y-%m-%d %H:%M:%S') if self.modify_at else None,
        )

    def link_pc_item(self):
        if self.commodity_url_refer:
            return '<a href="%s" target="_blank">%s</a>' %(self.commodity_url_refer, self.article_title)
        else:
            return '<a href="%s" target="_blank">%s</a>' %(self.commodity_url, self.article_title)
    link_pc_item.allow_tags = True
    link_pc_item.short_description = '商品PC推荐链接'

    def link_mobile_item(self):
        if self.commodity_url_refer_mb:
            return '<a href="%s" target="_blank">%s</a>' %(self.commodity_url_refer_mb, self.article_title)
        else:
            return '<a href="%s" target="_blank">%s</a>' %(self.commodity_url, self.article_title)
    link_mobile_item.allow_tags = True
    link_mobile_item.short_description = '商品移动推荐链接'

    def list_link_item(self):
        if self.commodity_url_refer:
            return '<a href="%s" target="_blank">%s</a>' %(self.commodity_url_refer, self.article_mall)
        elif self.commodity_url:
            return '<a href="%s" target="_blank">%s</a>' %(self.commodity_url, self.article_mall)
        else:
            return self.article_mall
    list_link_item.allow_tags = True
    list_link_item.short_description = '推荐链接'

    def item_title_summary(self):
        return (self.article_title[:25] + '..') if len(self.article_title) > 25 else self.article_title
    item_title_summary.allow_tags = True
    item_title_summary.short_description = '商品名称'

    @staticmethod
    def query_top_items_by(keyword, length):
        date_before_30_days = get_date_by_delta(datetime.datetime.today(), -30)
        result = None
        try:
            int(keyword)
            result = Item.objects.filter(Q(create_at__gte=date_before_30_days) & Q(active=True) & Q(article_id=keyword) | Q(id=keyword)).order_by('-modify_at').order_by('-create_at')
        except:
            pass
        if result and len(result) > 0:
            return result
        else:
            return Item.objects.filter(create_at__gte=date_before_30_days, article_title__icontains=keyword, active=True).order_by('-modify_at').order_by('-create_at')[:length]

class Keyword(models.Model):
    name =  models.CharField(max_length=50, null=True, blank=True, verbose_name='关键字名称')
    remarks = models.TextField(null=True, blank=True, verbose_name='关键字备注')
    subscribe_times = models.IntegerField(default=0, verbose_name='用户订阅数')
    create_at = models.DateTimeField(auto_now_add=True,verbose_name='创建时间')
    modify_at = models.DateTimeField(blank=True,null=True,verbose_name='修改时间')

    def save(self, *args, **kwargs):
        self.modify_at = datetime.datetime.today()
        self.subscribe_times = len(self.uservskeyword_set.all())
        return super(Keyword, self).save(*args, **kwargs)

    class Meta:
        verbose_name = '关键字'
        verbose_name_plural = '关键字'
        ordering = ('-modify_at', '-create_at')

    def __str__(self):
        return str(self.name)

class UserVsKeyword(models.Model):
    user = models.ForeignKey(UserProfile, verbose_name='用户')
    keyword = models.ForeignKey(Keyword, verbose_name='关键字')
    include = models.CharField(max_length=100, null=True, blank=True, verbose_name='包含词语')
    exclude = models.CharField(max_length=100, null=True, blank=True, verbose_name='排除词语')
    active = models.BooleanField(default=True, verbose_name='有效')
    notify_times = models.IntegerField(default=0, verbose_name='通知次数')
    expire_at = models.DateTimeField(blank=True,null=True,verbose_name='过期时间')
    create_at = models.DateTimeField(auto_now_add=True,verbose_name='创建时间')
    modify_at = models.DateTimeField(blank=True,null=True,verbose_name='修改时间')
    def save(self, *args, **kwargs):
        self.modify_at = datetime.datetime.today()
        if not self.expire_at:
            self.expire_at = datetime.date.today() + datetime.timedelta( days = 30 )
        return super(UserVsKeyword, self).save(*args, **kwargs)

    class Meta:
        verbose_name = '关键字:用户'
        verbose_name_plural = '关键字:用户'
        ordering = ('-modify_at', '-create_at')

    def __str__(self):
        return str(self.keyword.name)


QRCODE_TYPE = (
    ('0', '临时二维码'),
    ('1', '永久二维码'),
)

SHARE_TYPE = (
    ('0', '关注海报'),
    ('1', '商品页'),
    ('2', '专题页'),
)

class UserShare(models.Model):
    owner = models.ForeignKey(User, verbose_name='分享人')
    qrcode_type  = models.CharField(max_length=1, null=True, blank=True, verbose_name='二维码类型', choices=QRCODE_TYPE, default='0')
    share_type   = models.CharField(max_length=2, null=True, blank=True, verbose_name='分享类型', choices=SHARE_TYPE, default='0')
    goods_item = models.ForeignKey(Item, null=True, blank=True, verbose_name='商品')
    goods_url =  models.URLField(max_length=200, null=True, blank=True, verbose_name='商品页')
    subject_url = models.URLField(max_length=200, null=True, blank=True, verbose_name='专题页')
    qrcode_ticket = models.CharField(max_length=150, null=True, blank=True, verbose_name='二维码ticket', help_text='https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=#ticket#')
    qrcode_expire_at = models.DateTimeField(blank=True, null=True, verbose_name='二维码过期时间')
    active = models.BooleanField(default=True, verbose_name='有效')
    is_redirect = models.BooleanField(default=False, verbose_name='是否直接跳转')
    create_at = models.DateTimeField(auto_now_add=True,verbose_name='创建时间')
    modify_at = models.DateTimeField(blank=True,null=True,verbose_name='修改时间')

    def save(self, *args, **kwargs):
        self.modify_at = datetime.datetime.today()
        return super(UserShare, self).save(*args, **kwargs)

    class Meta:
        verbose_name = '用户分享'
        verbose_name_plural = '用户分享'
        ordering = ('-modify_at', '-create_at')

    def __str__(self):
        if self.goods_item is not None:
            data = self.goods_item.article_title
            return '%s分享了%s' %(self.owner.profile.nickname, (data[:9] + '..') if len(data) > 9 else data)
        else:
            if self.share_type == '0':
                return '%s分享了关注海报' %self.owner.profile.nickname
            elif self.share_type == '2':
                return '%s分享了专题页' %self.owner.profile.nickname
            else:
                return ''


    def display_qrcode(self):
        if self.qrcode_ticket:
            return '<img style="width:200px;height:200px;" src="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s" alt="qrcode" />' % self.qrcode_ticket
        else:
            return '<img style="width:200px;height:200px;" src="#" alt="qrcode"/>'
    display_qrcode.allow_tags = True
    display_qrcode.short_description = '二维码图片'

    def link_item(self):
        if self.goods_item:
            return '<a href="/admin/account/item/%d/" target="_blank">%s</a>' %(self.goods_item.id, self.goods_item.article_title)
        else:
            return None
    link_item.allow_tags = True
    link_item.short_description = '商品链接'

class UserShareFollow(models.Model):
    share = models.ForeignKey(UserShare, verbose_name='用户分享', related_name='share_members')
    user  = models.ForeignKey(User, verbose_name='用户')
    create_at = models.DateTimeField(auto_now_add=True,verbose_name='创建时间')
    modify_at = models.DateTimeField(blank=True,null=True,verbose_name='修改时间')

    def save(self, *args, **kwargs):
        self.modify_at = datetime.datetime.today()
        return super(UserShareFollow, self).save(*args, **kwargs)

    class Meta:
        verbose_name = '用户分享关注'
        verbose_name_plural = '用户分享关注'
        ordering = ('-modify_at', '-create_at')

    def __str__(self):
        return self.share.goods_item.article_title if self.share.goods_item else ''
